import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaPlayer.Status;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.io.File;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

public class JMusicPlayer extends Application {

    String iconSrc = "img/icon.png";
    String title = "JMusicPlayer";
    private MediaPlayer mediaPlayer;
    private Label playTime;
    private Slider timeSlider;
    private Slider volumeSlider;
    private final List

            <File>

            musicList = new ArrayList<>();
    private final ObservableList
            <File>

            observableMusicList = FXCollections.observableList(musicList);
    private int currentSongIndex = 0;
    private Label songNameLabel;

    @Override
    public void start(final Stage primaryStage) {
        BorderPane root = new BorderPane();

        // 创建菜单栏和菜单项
        MenuBar menuBar = new MenuBar();
        Menu fileMenu = new Menu("文件");
        MenuItem openFileItem = new MenuItem("打开文件");
        openFileItem.setOnAction(actionEvent -> {
            FileChooser fileChooser = new FileChooser();
            FileChooser.ExtensionFilter filter = new FileChooser.ExtensionFilter("MP3 文件 (*.mp3)", "*.mp3");
            fileChooser.getExtensionFilters().add(filter);
            File selectedFile = fileChooser.showOpenDialog(primaryStage);
            if (selectedFile != null) {
                try {
                    observableMusicList.add(selectedFile);
                    playMusic();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
        });
        MenuItem openFolderItem = new MenuItem("打开文件夹");
        openFolderItem.setOnAction(actionEvent -> {
            DirectoryChooser directoryChooser = new DirectoryChooser();
            File selectedDirectory = directoryChooser.showDialog(primaryStage);
            if (selectedDirectory != null) {
                File[] files = selectedDirectory.listFiles();
                if (files != null) {
                    for (File file : files) {
                        if (file.isFile() && file.getName().endsWith(".mp3")) {
                            observableMusicList.add(file);
                        }
                    }
                    try {
                        playMusic();
                    } catch (MalformedURLException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });
        MenuItem exitItem = new MenuItem("退出软件");
        exitItem.setOnAction(actionEvent -> System.exit(0));
        fileMenu.getItems().addAll(openFileItem, openFolderItem, new SeparatorMenuItem(), exitItem);
        menuBar.getMenus().add(fileMenu);

        // 创建播放、暂停、上一首、下一首按钮和音量控制Slider
        Button playButton = new Button("播放");
        playButton.setOnAction(actionEvent -> {
            Status status = mediaPlayer.getStatus();
            if (status == Status.UNKNOWN || status == Status.HALTED) {
                return;
            }

            if (status == Status.PAUSED || status == Status.READY || status == Status.STOPPED) {
                mediaPlayer.play();
                playButton.setText("播放");
            } else {
                mediaPlayer.pause();
                playButton.setText("暂停");
            }
        });

        Button previousSongButton = new Button("上一首");
        previousSongButton.setOnAction(actionEvent -> {
            if (currentSongIndex > 0 && !observableMusicList.isEmpty()) {
                currentSongIndex--;
                try {
                    playMusic();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
        });

        Button nextSongButton = new Button("下一首");
        nextSongButton.setOnAction(actionEvent -> {
            if (currentSongIndex < observableMusicList.size() - 1 && !observableMusicList.isEmpty()) {
                currentSongIndex++;
                try {
                    playMusic();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
        });

        volumeSlider = new Slider();
        volumeSlider.setPrefWidth(100);
        volumeSlider.setValue(50);
        volumeSlider.valueProperty().addListener(observable -> {
            if (volumeSlider.isValueChanging()) {
                mediaPlayer.setVolume(volumeSlider.getValue() / 100.0);
            }
        });

        // Create a Playtime Label and a progress Slider
        playTime = new Label();

        playTime.setText("00:00" + "/" + "00:00");

        timeSlider = new Slider();
        HBox timeHBox = new HBox(10, playTime, timeSlider);

        timeHBox.setAlignment(Pos.CENTER);

        // Create a playlist ListView
        ListView<File> musicListView = new ListView<>(observableMusicList);
        musicListView.getSelectionModel().selectedItemProperty().addListener((observableValue, oldFile, newFile) -> {
            if (newFile != null) {
                currentSongIndex = observableMusicList.indexOf(newFile);
                try {
                    playMusic();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
        });

        // Add delete button
        Button deleteButton = new Button("删除");
        deleteButton.setOnAction(actionEvent -> {
            observableMusicList.remove(currentSongIndex);
            if (observableMusicList.isEmpty()) {
                mediaPlayer.stop();
                songNameLabel.setText("");
                playTime.setText("");
            } else {
                currentSongIndex %= observableMusicList.size();
                try {
                    playMusic();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
        });

        // Create the song name Label and the lyrics TextArea
        songNameLabel = new Label();

        // Add the control to the VBox
        VBox vBox = new VBox(10);
        vBox.setPadding(new Insets(10));
        vBox.setAlignment(Pos.CENTER);

        HBox hBox = new HBox(10);
        hBox.getChildren().addAll(playButton, previousSongButton, nextSongButton,deleteButton, new Label("音量:"), volumeSlider);
        hBox.setAlignment(Pos.CENTER);
        vBox.getChildren().addAll(menuBar, hBox, timeHBox, musicListView, songNameLabel);

        root.setCenter(vBox);

        Scene scene = new Scene(root, 500, 400);
        primaryStage.setScene(scene);
        primaryStage.getIcons().add(new Image(iconSrc));
        primaryStage.setTitle(title);
        primaryStage.show();
    }

    private void playMusic() throws MalformedURLException {

        File file = observableMusicList.get(currentSongIndex);
        Media media = new Media(file.toURI().toURL().toString());

        if (mediaPlayer != null) {
            mediaPlayer.dispose();
        }

        mediaPlayer = new MediaPlayer(media);

        // 删除按钮控制程序
        mediaPlayer.setOnEndOfMedia(() -> {
            if (currentSongIndex < observableMusicList.size() - 1) {
                currentSongIndex++;
                try {
                    playMusic();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            } else {
                mediaPlayer.stop();
                songNameLabel.setText("");
                playTime.setText("");
            }
        });

        mediaPlayer.play();

        mediaPlayer.setOnReady(() -> {
            timeSlider.setMin(0);
            timeSlider.setMax(mediaPlayer.getMedia().getDuration().toSeconds());
            timeSlider.setValue(0);
            mediaPlayer.volumeProperty().bind(volumeSlider.valueProperty().divide(100));
            playTime.setText(formatTime(Duration.ZERO) + "/" + formatTime(mediaPlayer.getTotalDuration()));
            songNameLabel.setText("正在播放: " + file.getName());
        });

        mediaPlayer.currentTimeProperty().addListener((observableValue, oldValue, newValue) -> {
            if (!timeSlider.isValueChanging()) {
                timeSlider.setValue(newValue.toSeconds());
            }

            playTime.setText(formatTime(newValue) + "/" + formatTime(mediaPlayer.getTotalDuration()));
        });

        // Allow clicking anywhere on the time slider to move the current position
        timeSlider.setOnMousePressed(mouseEvent -> {
            if (!mediaPlayer.getMedia().getDuration().isUnknown()) {
                double width = timeSlider.getWidth();
                double mouseX = mouseEvent.getX();
                double percent = (mouseX / width);
                Duration duration = mediaPlayer.getMedia().getDuration();
                mediaPlayer.seek(duration.multiply(percent));
            }
        });

        // Allow dragging the time slider to move the current position
        timeSlider.setOnMouseDragged(mouseEvent -> {
            if (!mediaPlayer.getMedia().getDuration().isUnknown()) {
                double width = timeSlider.getWidth();
                double mouseX = mouseEvent.getX();
                double percent = (mouseX / width);
                Duration duration = mediaPlayer.getMedia().getDuration();
                mediaPlayer.seek(duration.multiply(percent));
            }
        });
    }

    private String formatTime(Duration duration) {
        int seconds = (int) duration.toSeconds();
        return String.format("%02d:%02d", seconds / 60, seconds % 60);
    }

    public static void main(String[] args) {
        launch(args);
    }
}